package cn.devices.service.impl;

import cn.devices.entity.TbCodeGen;
import cn.devices.mapper.TbCodeGenMapper;
import cn.devices.service.TbCodeGenService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * <p>
 * 编号生成表 服务实现类
 * </p>
 *
 * @author 秋水浮萍
 * @since 2021-02-24
 */
@Service
public class TbCodeGenServiceImpl implements TbCodeGenService {

    @Autowired
    private TbCodeGenMapper mapper;
    private DateFormat dateTimeFormat = new SimpleDateFormat("yyyyMMdd");

    @Override
    @Transactional(isolation = Isolation.DEFAULT)
    public String genCode(String codeName) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MILLISECOND, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        Date date = calendar.getTime();
        TbCodeGen codeGen = mapper.get(codeName);
        if (codeGen == null) return null;
        else if (codeGen.getCodeTm().equals(date)) {
            codeGen.setCodeValue(codeGen.getCodeValue() + codeGen.getValueIncrement());
            mapper.update(codeGen);
            return buildCode(codeGen);
        } else {
            codeGen.setCodeValue(1);
            codeGen.setCodeTm(date);
            mapper.update(codeGen);
            return buildCode(codeGen);
        }
    }
    private String buildCode(TbCodeGen gen) {
        String dateStr = dateTimeFormat.format(gen.getCodeTm());
        StringBuffer buffer = new StringBuffer();
        buffer.append(gen.getCodeName());
        buffer.append(dateStr);
        int len = String.valueOf(gen.getCodeValue()).length();
        if (len >= gen.getValueLength()) {
            buffer.append(String.valueOf(gen.getCodeValue()));
        } else {

            buffer.append(String.format("%0" + gen.getValueLength() + "d", gen.getCodeValue()));
        }
        return buffer.toString();
    }
}
